﻿using System.Runtime.Remoting.Messaging;
using System.Web;
using NHibernate;
using NHibernate.Cfg;
using System.Xml;
using System.Diagnostics;

namespace NHibernate_1
{
    public static class Domain
    {
        private const string sessionKey = "NHib.SessionKey";
        private static ISessionFactory sessionFactory;

        public static ISession CurrentSession
        {
            get
            {
                return GetSession(true);
            }
        }

        static Domain()
        {
        }

        public static void Init()
        {
            sessionFactory = new Configuration().Configure("Nhibernate.cfg.xml").BuildSessionFactory();
        }

        public static void Close()
        {
            ISession currentSession = GetSession(false);

            if (currentSession != null)
            {
                currentSession.Close();
            }
        }

        private static ISession GetSession(bool getNewIfNotExists)
        {
            ISession currentSession;

            currentSession = CallContext.GetData(sessionKey) as ISession;

            if (currentSession == null && getNewIfNotExists)
            {
                currentSession = sessionFactory.OpenSession();
                CallContext.SetData(sessionKey, currentSession);
            }

            return currentSession;
        }
    }
}